package com.ddm.controller.vx;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ddm.dto.page.PageQueryDTO;
import com.ddm.entity.Bookmark;
import com.ddm.entity.LevelEntity;
import com.ddm.result.PageResult;
import com.ddm.result.Result;
import com.ddm.service.vxService.BookmarkService;
import com.ddm.vo.vxVo.IfBookmark;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 丁丁猫
 * @version 1.0
 */
@RestController
@RequestMapping("/user/bookmark")
@Slf4j
public class BookmarkController {

    @Autowired
    private BookmarkService bookmarkService;

    /**
     * 新增收藏记录
     *
     * @param bm
     * @return
     */
    @ApiOperation("新增收藏记录")
    @PostMapping
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public Result<String> addBookmark(@RequestBody Bookmark bm) {
        Long userId = bm.getUserId();
        Long standardId = bm.getStandardId();
        Integer level = bm.getLevel();
        Long levelId = bm.getLevelId();
        log.info("新增收藏记录 userId:{}, standardId:{}, level:{}, levelId:{}", userId, standardId, level, levelId);
        Bookmark bookmark = new Bookmark();
        bookmark.setUserId(userId);
        bookmark.setStandardId(standardId);
        bookmark.setLevel(level);
        bookmark.setLevelId(levelId);
        bookmarkService.save(bookmark);
        return Result.success("收藏成功");
    }

    /**
     * 分页查询收藏记录 by userId
     *
     * @param userId
     * @param pageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询收藏记录")
    public Result<PageResult> page(@RequestParam Long userId, PageQueryDTO pageQueryDTO) {
        log.info("根据关键词分页查询标准文档");
        PageResult pageResult = bookmarkService.pageQueryByUserId(pageQueryDTO, userId);
        return Result.success(pageResult);
    }

    /**
     * 查询单个用户收藏的指标
     *
     * @param standardId
     * @param level
     * @param levelId
     * @return
     */
    @ApiOperation("查询单个用户收藏的指标")
    @GetMapping
    public Result<LevelEntity> searchBookmark(@RequestParam Long standardId,
                                              @RequestParam Integer level,
                                              @RequestParam Long levelId) {
        log.info("查询单个用户收藏的指标 standardId:{}, level:{}, levelId:{}", standardId, level, levelId);
        LevelEntity l = bookmarkService.searchBookmark(standardId, level, levelId);
        return Result.success(l);
    }


    /**
     * 删除单个用户收藏指标
     *
     * @param bm
     * @return
     */
    @ApiOperation("删除单个用户收藏指标")
    @DeleteMapping
    public Result<String> deleteBookmark(@RequestBody Bookmark bm) {
        log.info("删除单个用户收藏指标");
        int delete = bookmarkService.deleteBookmark(bm.getUserId(), bm.getStandardId(), bm.getLevel(), bm.getLevelId());
        return Result.success("删除成功");
    }

    /**
     * 判断该指标是否被某个用户收藏
     * @param standardId
     * @param level
     * @param levelId
     * @param userId
     * @return
     */
    @ApiOperation("判断该指标是否被某个用户收藏")
    @GetMapping("/ifbookmark")
    public Result<IfBookmark> ifbookmark(@RequestParam Long standardId,
                                         @RequestParam Integer level,
                                         @RequestParam Long levelId,
                                         @RequestParam Long userId) {
        log.info("判断该指标是否被某个用户收藏");
        QueryWrapper<Bookmark> eq = new QueryWrapper<Bookmark>()
                .eq("user_id", userId)
                .eq("standard_id", standardId)
                .eq("level", level)
                .eq("level_id", levelId);
        Bookmark entity = bookmarkService.getOne(eq);
        IfBookmark ifBookmark = new IfBookmark();
        if (entity != null) {
            ifBookmark.setIfbookmark(1);
        } else {
            ifBookmark.setIfbookmark(0);
        }
        return Result.success(ifBookmark);
    }
    
    /**
     * 竞赛报名（收藏即报名）
     *
     * @param bm 包含userId和exam_id的收藏实体
     * @return
     */
    @ApiOperation("竞赛报名")
    @PostMapping("/register-exam")
    public Result<String> registerExam(@RequestBody Bookmark bm) {
        Long userId = bm.getUserId();
        Long examId = bm.getExam_id();
        log.info("竞赛报名 userId:{}, examId:{}", userId, examId);
        
        if (userId == null) {
            return Result.error("请先登录");
        }
        if (examId == null) {
            return Result.error("竞赛ID不能为空");
        }
        
        Bookmark bookmark = new Bookmark();
        bookmark.setUserId(userId);
        bookmark.setExam_id(examId);
        bookmarkService.save(bookmark);
        return Result.success("竞赛报名成功");
    }
    
    /**
     * 取消竞赛报名
     *
     * @param bm 包含userId和exam_id的收藏实体
     * @return
     */
    @ApiOperation("取消竞赛报名")
    @DeleteMapping("/cancel-exam-registration")
    public Result<String> cancelExamRegistration(@RequestBody Bookmark bm) {
        Long userId = bm.getUserId();
        Long examId = bm.getExam_id();
        log.info("取消竞赛报名 userId:{}, examId:{}", userId, examId);
        
        if (userId == null) {
            return Result.error("请先登录");
        }
        if (examId == null) {
            return Result.error("竞赛ID不能为空");
        }
        
        QueryWrapper<Bookmark> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("exam_id", examId);
        boolean deleted = bookmarkService.remove(queryWrapper);
        
        if (deleted) {
            return Result.success("取消报名成功");
        } else {
            return Result.error("取消报名失败，未找到对应报名记录");
        }
    }
    
    /**
     * 检查竞赛报名状态
     *
     * @param userId 用户ID
     * @param examId 竞赛ID
     * @return
     */
    @ApiOperation("检查竞赛报名状态")
    @GetMapping("/check-exam-registration")
    public Result<IfBookmark> checkExamRegistration(@RequestParam Long userId, @RequestParam Long examId) {
        log.info("检查竞赛报名状态 userId:{}, examId:{}", userId, examId);
        
        boolean isRegistered = bookmarkService.checkExamRegistration(userId, examId);
        IfBookmark ifBookmark = new IfBookmark();
        if (isRegistered) {
            ifBookmark.setIfbookmark(1);
        } else {
            ifBookmark.setIfbookmark(0);
        }
        return Result.success(ifBookmark);
    }
    
    /**
     * 获取用户报名的竞赛列表
     *
     * @param userId 用户ID
     * @return
     */
    @ApiOperation("获取用户报名的竞赛列表")
    @GetMapping("/registered-exams")
    public Result<List<Long>> getRegisteredExams(@RequestParam Long userId) {
        log.info("获取用户报名的竞赛列表 userId:{}", userId);
        
        List<Long> examIds = bookmarkService.getRegisteredExamIds(userId);
        return Result.success(examIds);
    }
}
